from sanic import Sanic
from sanic.response import json
from sanic.request import Request
import asyncio


import os
import time
from multiprocessing import Process
import setproctitle

from asyncio.unix_events import _UnixDefaultEventLoopPolicy
from asyncio.base_events import BaseEventLoop


def test2(aa):
    print("test2")
    time.sleep(10)
    aa["res"] = "sdsdsd"
    os._exit(22)
    return "sdsdsdsd"

def worker():
    aa = {}
    p = Process(target=test2, name="worker xxxx", args=(aa,))
    p.start()
    res = p.join()
    print(aa)
    return "ok"


app = Sanic()

# @app.route("/", methods=["POST"])
# async def test(request: Request):
#     print(request.json)
#     p = Process(target=worker, name="worker xxxx", args=())
#     setproctitle.setproctitle("mainxxxxx")
#     p.start()
#     p.join()
#     print("主进程终止")
#     return json({"hello": "world"})


@app.route("/", methods=["POST"])
async def test(request: Request):
    print(request.json)
    loop = asyncio.get_event_loop()
    res = await loop.run_in_executor(None, worker)
    return json({"hello": res})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000, debug=True)